package com.solocredit.finance.ui.steps.adapter

import android.graphics.Color
import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.solocredit.finance.R
import com.solocredit.finance.base.adapter.MullaRecyclerViewAdapter
import com.solocredit.finance.base.adapter.MullaViewHolderHelper
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.SharedHelper
import com.solocredit.finance.weight.input.TimeStampEditText
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/30 13:54
 * @Annotation：认证流程步骤适配器
 */
class MullaStepCommonAdapter(recyclerView: RecyclerView?): MullaRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//时间选择
                return R.layout.item_mulla_step_common_select
            }
            "GENDER_PICK" -> {//性别
                return R.layout.item_mulla_step_common_gender
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                return R.layout.item_mulla_step_phonebook_relation
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.item_mulla_step_common_mobile
            }
            "SELECT" -> {//选择
                return R.layout.item_mulla_step_common_select
            }
            else -> {//输入框
                return R.layout.item_mulla_step_common_input
            }
        }
    }

    override fun setItemChildListener(helper: MullaViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.selectLayout)//选择
        helper.setItemChildClickListener(R.id.imgPhoneBook)//选择联系人
        helper.setItemChildClickListener(R.id.textMobile)
    }

    override fun fillData(helper: MullaViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val textTitle = helper.getTextView(R.id.textTitle)
        var showTitle = model.optString("title")
        if (MullaConfigs.isSwahili()){
            showTitle = model.optString("title_sw")
        }
        textTitle.text = findKeywordColor(Color.parseColor("#FFFF4D3E"),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showMullaSelectView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showMullaPhoneBookRelationView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showMullaPhoneBookMobileView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showMullaSelectGender(helper,position,model)
            }
            else -> {//输入框
                showMullaInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showMullaInputView(helper: MullaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val editText = helper.getView<TimeStampEditText>(R.id.editText)
        var showHint = model.optString("hint")
        if (MullaConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        editText.setHint(showHint)
        editText.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            val showTitle = selectItem.optString("title")
            showText = showTitle
        }
        editText.setText(showText)
        editText.setInputFocusChangeListener(object : TimeStampEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus){
                    editText.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
                } else {
                    editText.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
                }
            }
            override fun onEditSubmitPointAction(v: View?, remark: String) {
                var eventType = String.format(MullaEventType.FORM.MULLA_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "PHONEBOOK"){
                    eventType = String.format(MullaEventType.FORM.MULLA_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addMullaEventAction(eventType,remark)
            }
        })
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }

        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择性别
     */
    private fun showMullaSelectGender(helper: MullaViewHolderHelper, position: Int, model: JSONObject){
        val itemLayout1 = helper.getView<LinearLayout>(R.id.itemLayout1)
        itemLayout1.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
        val imgGender1 = helper.getImageView(R.id.imgGender1)
        val textValue1 = helper.getTextView(R.id.textValue1)
        textValue1.setTextColor(Color.parseColor("#FF999999"))
        textValue1.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
        val imgSelect1 = helper.getImageView(R.id.imgSelect1)
        imgSelect1.setImageResource(R.mipmap.mulla_checkbox_normal)

        val itemLayout2 = helper.getView<LinearLayout>(R.id.itemLayout2)
        itemLayout2.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
        val imgGender2 = helper.getImageView(R.id.imgGender2)
        val textValue2 = helper.getTextView(R.id.textValue2)
        textValue2.setTextColor(Color.parseColor("#FF999999"))
        textValue2.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
        val imgSelect2 = helper.getImageView(R.id.imgSelect2)
        imgSelect2.setImageResource(R.mipmap.mulla_checkbox_normal)

        val values = model.optJSONArray("values")
        if (values != null){
            if (values.length() > 0){
                val item = values.optJSONObject(0)
                var showTitle = item.optString("title")
                if (MullaConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                textValue1.text = showTitle
                if (item.optString("value") == "MALE" || item.optString("value") == "mâle"){
                    imgGender1.setImageResource(R.mipmap.mulla_step_gender_male)
                } else {
                    imgGender1.setImageResource(R.mipmap.mulla_step_gender_female)
                }
            }
            if (values.length() > 1){
                val item = values.optJSONObject(1)
                var showTitle = item.optString("title")
                if (MullaConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                textValue2.text = showTitle
                if (item.optString("value") == "MALE" || item.optString("value") == "mâle"){
                    imgGender2.setImageResource(R.mipmap.mulla_step_gender_male)
                } else {
                    imgGender2.setImageResource(R.mipmap.mulla_step_gender_female)
                }
            }
        }

        //选中
        if (model.has("selectItem")){
            val selectValue = model.getJSONObject("selectItem")
            if (values != null){
                if (values.length() > 0){
                    val item = values.optJSONObject(0)
                    if (item.optString("title") == selectValue.optString("title")){
                        itemLayout1.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
                        textValue1.setTextColor(Color.parseColor("#FF000000"))
                        textValue1.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                        imgSelect1.setImageResource(R.mipmap.mulla_checkbox_select)
                    }
                }
                if (values.length() > 1){
                    val item = values.optJSONObject(1)
                    if (item.optString("title") == selectValue.optString("title")){
                        itemLayout2.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
                        textValue2.setTextColor(Color.parseColor("#FF000000"))
                        textValue2.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                        imgSelect2.setImageResource(R.mipmap.mulla_checkbox_select)
                    }
                }
            }
        }

        itemLayout1.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(0)
                model.put("selectItem", item)
                HttpHelper.addMullaEventAction(String.format(MullaEventType.CLICK.MULLA_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }

        itemLayout2.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(1)
                model.put("selectItem", item)
                HttpHelper.addMullaEventAction(String.format(MullaEventType.CLICK.MULLA_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }
    }

    /**
     * 选择类型
     */
    private fun showMullaSelectView(helper: MullaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (MullaConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val textValue = helper.getTextView(R.id.textValue)
        textValue.setHint(showHint)
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (MullaConfigs.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            textValue.text = showTitle
        }
    }

    /**
     * 联系人关系
     */
    private fun showMullaPhoneBookRelationView(helper: MullaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (MullaConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        //选择关系
        val textValue = helper.getTextView(R.id.textValue)
        textValue.setHint(showHint)
        //输入关系
        val editText = helper.getView<TimeStampEditText>(R.id.editText)
        editText.setHint(mContext.getString(R.string.step_phonebook_relation_enter))
        editText.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
        editText.visibility = View.GONE

        var showTitle = ""
        var showOtherValue = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            showTitle = selectItem.optString("title")
            if (MullaConfigs.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            if (showTitle == mContext.getString(R.string.step_phonebook_relation_other)){
                editText.visibility = View.VISIBLE
                if (selectItem.has("otherValue")){
                    showOtherValue = selectItem.optString("otherValue","")
                }
            }
        }
        textValue.text = showTitle

        //关系为“Other”时，输入框允许输入
        editText.isEnabled = showTitle == mContext.getString(R.string.step_phonebook_relation_other)
        editText.setText(showOtherValue)
        editText.setInputFocusChangeListener(object : TimeStampEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus){
                    editText.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
                } else {
                    editText.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
                }
            }
            override fun onEditSubmitPointAction(v: View?, remark: String) {
                var eventType = String.format(MullaEventType.FORM.MULLA_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "PHONEBOOK"){
                    eventType = String.format(MullaEventType.FORM.MULLA_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addMullaEventAction(eventType,remark)
            }
        })
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }

        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.getJSONObject("selectItem")
                    selectItem.put("otherValue",s.toString())
                }
            }
        })
    }

    /**
     * 联系电话
     */
    private fun showMullaPhoneBookMobileView(helper: MullaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (MullaConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val textMobile = helper.getTextView(R.id.textMobile)
        textMobile.setHint(showHint)
        val editMobile = helper.getView<EditText>(R.id.editMobile)
        editMobile.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            textMobile.text = showValue
            editMobile.setText(showValue)
        }
        editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editMobile.clearFocus()
                true
            }
            false
        }
        editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                editMobile.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
                HttpHelper.addMullaEventAction(String.format(MullaEventType.FORM.MULLA_FORM_STEP_INPUT_XX,model.optString("paramName")),editMobile.text.toString())
            } else {
                editMobile.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
            }
        }
        editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //设备是否支持通讯录选择联系人
        if (model.optBoolean("isPhoneBookPick")){
            helper.setVisibility(R.id.imgPhoneBook,View.VISIBLE)
            //是否是审核账号
            val isConfigAccount = SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_IS_CONFIG_ACCOUNT)
            if(isConfigAccount){//审核账号 - 允许输入或选择
                textMobile.visibility = View.GONE
                editMobile.visibility = View.VISIBLE
            } else {//非审核账号只能选择
                textMobile.visibility = View.VISIBLE
                editMobile.visibility = View.GONE
            }
        } else {//不支持通讯录选择
            helper.setVisibility(R.id.imgPhoneBook,View.INVISIBLE)
            textMobile.visibility = View.GONE
            editMobile.visibility = View.VISIBLE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}